{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d566cc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from tqdm.notebook import tqdm\n",
    "import benchmark\n",
    "import utils\n",
    "from openai_cache import Completion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdaedc66",
   "metadata": {},
   "outputs": [],
   "source": [
    "def construct_placement_prompt(scenario):\n",
    "    placement_prompt_template = '''objects = {seen_objects_str}\n",
    "receptacles = {receptacles_str}\n",
    "{seen_placements_str}\n",
    "    \n",
    "objects = {unseen_objects_str}\n",
    "receptacles = {receptacles_str}\n",
    "pick_and_place(\"{first_object}\",'''\n",
    "    seen_objects_str = '[' + ', '.join(map(lambda x: f'\"{x}\"', scenario.seen_objects)) + ']'\n",
    "    receptacles_str = '[' + ', '.join(map(lambda x: f'\"{x}\"', scenario.receptacles)) + ']'\n",
    "    seen_placements_str = '\\n'.join(map(lambda x: f'pick_and_place(\"{x[0]}\", \"{x[1]}\")', scenario.seen_placements))\n",
    "    unseen_objects_str = '[' + ', '.join(map(lambda x: f'\"{x}\"', scenario.unseen_objects)) + ']'\n",
    "    return placement_prompt_template.format(\n",
    "        seen_objects_str=seen_objects_str, receptacles_str=receptacles_str,\n",
    "        seen_placements_str=seen_placements_str, unseen_objects_str=unseen_objects_str,\n",
    "        first_object=scenario.unseen_objects[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f622aade",
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate(scenarios, model='text-davinci-003', verbose=False):\n",
    "    completion = Completion()\n",
    "    accuracies = []\n",
    "    for i, scenario in enumerate(tqdm(scenarios)):\n",
    "        if verbose:\n",
    "            print(f'Scenario {i + 1} of {len(scenarios)}\\n')\n",
    "\n",
    "        # Object placement\n",
    "        placement_prompt = construct_placement_prompt(scenario)\n",
    "        placement_completion = completion.create(placement_prompt, model)['choices'][0]['text']\n",
    "        if verbose:\n",
    "            print(placement_prompt, end='')\n",
    "            utils.print_colored(placement_completion, 'blue')\n",
    "            print('\\n' + 10 * '-' + '\\n')\n",
    "\n",
    "        # Analysis\n",
    "        predicted_placements = benchmark.parse_placements(placement_completion, scenario.unseen_objects)\n",
    "        corrects, accuracy = benchmark.check_placements(predicted_placements, scenario.unseen_placements)\n",
    "        accuracies.append(accuracy)\n",
    "        if verbose:\n",
    "            print(f'Annotator notes: {scenario.annotator_notes}\\n')\n",
    "            print('Correct placements:')\n",
    "            for placement in scenario.unseen_placements:\n",
    "                print(placement)\n",
    "            print('\\nParsed placements:')\n",
    "            for placement, correct in zip(predicted_placements, corrects):\n",
    "                utils.print_colored(placement, 'green' if correct else 'red')\n",
    "            print(f'\\nAccuracy: {accuracy:.2f}')\n",
    "            print('\\n' + 80 * '-' + '\\n')\n",
    "    return accuracies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8bcd7db",
   "metadata": {},
   "outputs": [],
   "source": [
    "scenarios = benchmark.load_scenarios()\n",
    "len(scenarios)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9057ecb4",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "#accuracies = evaluate(scenarios, verbose=True)\n",
    "accuracies = evaluate(scenarios)\n",
    "np.mean(accuracies).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1da4f65d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
